package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.Result;
import com.sky.service.UserDishService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {
	
	private final DishMapper dishMapper;
	private final DishFlavorMapper dishFlavorMapper;
	private final SetmealDishMapper setmealDishMapper;
	
	public UserDishServiceImpl(DishMapper dishMapper, DishFlavorMapper dishFlavorMapper, SetmealDishMapper setmealDishMapper) {
		this.dishMapper = dishMapper;
		this.dishFlavorMapper = dishFlavorMapper;
		this.setmealDishMapper = setmealDishMapper;
	}
	
	@Override
	@Cacheable(cacheNames = "DishCache", key = "#categoryId", unless = "#result.data.size()==0")
	public Result<List<DishVO>> dishList(Long categoryId) {
		if (categoryId == null) {
			return Result.error(MessageConstant.INCORRECT_PARAMETERS);
		}
		
		List<Dish> dishList = dishMapper.getByCategoryId(categoryId);
		if (dishList.isEmpty()) {
			return Result.error(MessageConstant.DISH_NOT_FOUND);
		}
		List<DishVO> dishVOList = new ArrayList<>();
		dishList.forEach(dish -> {
			DishVO dishVO = new DishVO();
			BeanUtils.copyProperties(dish, dishVO);
			List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());
			dishVO.setFlavors(flavors);
			dishVOList.add(dishVO);
		});
		return Result.success(dishVOList);
	}
	
	@Override
	@Cacheable(cacheNames = "DishCache", key = "#id")
	public Result userDishService(Long id) {
		List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
		List<DishItemVO> dishItemVOS = new ArrayList<>();
		setmealDishes.forEach(setmealDish -> {
			DishItemVO dishItemVO = new DishItemVO();
			BeanUtils.copyProperties(setmealDish, dishItemVO);
			dishItemVOS.add(dishItemVO);
		});
		return Result.success(dishItemVOS);
	}
}
